<!--
 * @Date: 2025-02-28 13:46:14
 * @LastEditors: MsChen Your email MsChen
 * @LastEditTime: 2025-02-28 15:05:42
 * @FilePath: /finance/Users/chenyufan/Downloads/框架/glm-mes-pc-ui/glm-mes-pc-MES_框架/src/views/logistics/Statistics/CostRatioPage.vue
-->
<template>
	<div class="demo-date-picker">
			<div class="block">
				年月：
			</div>
			<div class="block">
				<el-date-picker v-model="orderStartTime" type="month" placeholder="开始年月" />
			</div>
			<span class="block">至</span>
			<div class="block">
				<el-date-picker v-model="orderEndTime" type="month" placeholder="结束年月" />
			</div>
			<div style="margin-left: 10px;">
				<el-button @click="fetchData()">查询</el-button>
				<el-button @click="fetchData(6)">上个月</el-button>
				<el-button @click="fetchData(7)">本月</el-button>
				<el-button @click="fetchData(8)">半年</el-button>
				<el-button @click="fetchData(9)">本年</el-button>
			</div>
	</div>
	<div id="chart" style="width: 100%; height: 90vh"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { getCostRatioAPI } from '@/api/Statistics'
import { onMounted } from 'vue'
const { proxy } = getCurrentInstance()
const chartData = ref({
	xAxis: [],
	series: [],
	rawData: []
})
//接口请求参数
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth();
let orderStartTime = ref(new Date(currentYear, currentMonth))
let orderEndTime = ref(new Date(currentYear, currentMonth))
// let queryType = ref(9)

const fetchData = async (prame) => {
    // 校验开始时间不能大于结束时间
    if (orderStartTime.value > orderEndTime.value) {
        proxy.$modal.msgError('开始时间不能大于结束时间')
        return
    }
	try {
      let params = {
          orderStartTime: `${orderStartTime.value.getFullYear()}${String(orderStartTime.value.getMonth() + 1).padStart(2, '0')}`,
          orderEndTime:`${orderEndTime.value.getFullYear()}${String(orderEndTime.value.getMonth() + 1).padStart(2, '0')}`,
          queryType: prame
      };
		const { code, data } = await getCostRatioAPI(params)
		if (code === 200) {
			chartData.value = data
			renderChart()
		}
	} catch (error) {
		console.error('数据请求失败', error)
	}
}

let myChart = null
const renderChart = () => {

    if (!chartData.value) return
    if (!myChart) {
        myChart = echarts.init(document.getElementById('chart'))
    }

	// 获取 x 轴数据（月份）
	const xAxisData = chartData.value.xAxis
	// 获取 y 轴数据
	const rawData = chartData.value.rawData
	// 计算每个月的总费用
	const totalData = rawData[0].map((_, index) => rawData.reduce((sum, item) => sum + parseFloat(item[index]), 0))
	const series = chartData.value.series.map((name, sid) => ({
		name,
		type: 'bar',
		stack: 'total',
		barWidth: '60%',
		label: {
			show: true,
			formatter: (params) => Math.round(params.value * 10) / 10 + '%' // 保留1位小数
		},
		data: rawData[sid].map(
			(d, did) => (totalData[did] === 0 ? 0 : (parseFloat(d) / totalData[did]) * 100) // 计算百分比
		)
	}))
	// ECharts 配置项
	const option = {
		title: {
			text: '国内/国际快递费用占比',
			left: 'center'
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			},
			formatter: (params) => {
				let content = `${params[0].axisValue}月<br/>`
				params.forEach((item) => {
					content += `${item.marker} ${item.seriesName}: ${item.value.toFixed(2)}%<br/>`
				})
				return content
			}
		},
		legend: {
			data: chartData.value.series,
			top: '5%'
		},
		grid: {
			left: '10%',
			right: '10%',
			bottom: '10%',
			containLabel: true
		},
		xAxis: {
			type: 'category',
			data: xAxisData
		},
		yAxis: {
			type: 'value',
			min: 0,
			max: 100,
			axisLabel: {
				formatter: '{value} %'
			}
		},
		series
	}

	myChart.setOption(option,true)
}

onMounted(fetchData)
</script>
<style scoped>
.demo-date-picker {
	display: flex;
	align-items: center;
	width: 100%;
	padding: 0;
	flex-wrap: wrap;
}

.demo-date-picker .block {
	padding: 30px 0;
	text-align: center;
	margin-left: 10px;
	/* border-right: solid 1px var(--el-border-color); */
	/* flex: 1; */
}

.demo-date-picker .block:last-child {
	border-right: none;
}

.demo-date-picker .demonstration {
	display: block;
	color: var(--el-text-color-secondary);
	font-size: 14px;
	margin-bottom: 20px;
}
</style>
